package com.huluobo.user

import androidx.lifecycle.viewModelScope
import androidx.paging.Pager
import androidx.paging.PagingConfig
import androidx.paging.cachedIn
import com.huluobo.lib_base.BaseViewModel
import com.huluobo.lib_base.Res
import com.huluobo.lib_base.StateType
import com.huluobo.lib_base.UIIntent
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.flow.Flow
import javax.inject.Inject

/**
 *  Created by LC on 2025/8/27.
 */
@HiltViewModel
class UserViewModel @Inject constructor(private val userRepo: UserRepo) : BaseViewModel<UserIntent>() {
    override fun handleIntent(it: UIIntent) {
        when (it) {
            is UserIntent.AddEmployee -> {
                httpRequest(userRepo.addEmployee(it.map))
            }

            is UserIntent.Login -> {
                httpRequest(userRepo.login(it.map))
            }

            is UserIntent.AddApprove -> {
                httpRequest(userRepo.addApprove(it.map))
            }

            is UserIntent.GetApprove -> {
                httpRequest(userRepo.getApprove() as Flow<Res<Any>>)
            }

            is UserIntent.DeleteApprove -> {
                httpRequest(userRepo.deleteApprove(it.id), StateType.DELETE)
            }

            is UserIntent.ComApprove -> {
                httpRequest(userRepo.comApprove(it.map))
            }

            is UserIntent.LoginVideo -> {
                httpRequest(userRepo.loginVideo(it.map) as Flow<Res<Any>>, StateType.LOGIN)
            }
        }
    }

    //pageSize 每次加载的大小,prefetchDistance 预加载的大小
    //cachedIn 缓存到协程的作用域当中
    fun getPagingData() = Pager(PagingConfig(pageSize = 10, prefetchDistance = 25)) {
        ApprovePagingSource(userRepo = userRepo)
    }.flow.cachedIn(viewModelScope)
}